# coding=utf-8

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
from com.android.monkeyrunner import MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
from com.android.chimpchat.hierarchyviewer import HierarchyViewer
from com.android.hierarchyviewerlib.models import ViewNode
from datetime import datetime
import os,time,sys,traceback,os.path
sys.path.append(r"lib\ddmlib.jar")
from com.android.ddmlib import TimeoutException

coordinateMap = {}

def getChildView(device, parentId, *childSeq):
	#print str(childSeq) 	
	str_getchildview="hierarchyViewer.findViewById('" + parentId +"')"    
	for index in childSeq:       
		str_getchildview+=('.children[' + str(index) + ']') 
	hierarchyViewer = device.getHierarchyViewer()
	exec 'child_view=' + str_getchildview
	return child_view

def pressById(device, parentId, *childSeq):
	#print str(childSeq)
	hierarchyViewer = device.getHierarchyViewer()
	str_getchildview="hierarchyViewer.findViewById('" + parentId +"')"    
	for index in childSeq:       
		str_getchildview+=('.children[' + str(index) + ']') 
	exec 'child_view=' + str_getchildview

def pressById_1(device, parentId, pressKey, *childSeq):
	#print coordinateMap
	if coordinateMap.has_key(pressKey):
		printLog("Got "+ pressKey +" from coordinateMap")
		child_view_location = coordinateMap[pressKey]
	else:	
		hierarchyViewer = device.getHierarchyViewer()
		str_getchildview="hierarchyViewer.findViewById('" + parentId +"')"	
		for index in childSeq:	   
			str_getchildview+=('.children[' + str(index) + ']') 
		exec 'child_view=' + str_getchildview
		child_view_location = hierarchyViewer.getAbsoluteCenterOfView(child_view)
		coordinateMap[pressKey] = child_view_location
	x = child_view_location.x
	y = child_view_location.y
	device.touch(x, y, "DOWN_AND_UP")
	MonkeyRunner.sleep(2)
	return

def pressByIdRelative(device, parentId, task_high, *childSeq):
	hierarchyViewer = device.getHierarchyViewer()
	root_node = hierarchyViewer.findViewById("id/content")
	screen_high = device.getProperty('display.height')
	screen_width = device.getProperty('display.width')
	current_high = root_node.height 
	current_width = root_node.width  
	top_space = int(((int(screen_high)-task_high) - current_high)/2)
	left_space = int((int(screen_width)-current_width)/2)
	str_getchildview="hierarchyViewer.findViewById('" + parentId +"')"	
	for index in childSeq:	   
		str_getchildview+=('.children[' + str(index) + ']') 
	exec 'child_view=' + str_getchildview
	child_view_location = HierarchyViewer.getAbsoluteCenterOfView(child_view)
	#print parentId + "=" + str(child_view_location.x) + ":" + str(child_view_location.y)
	x = child_view_location.x + left_space
	y = child_view_location.y + top_space + task_high
	#print "x="+str(x)+" y="+str(y) 
	device.touch(x, y, "DOWN_AND_UP")
	MonkeyRunner.sleep(2)
	return

def getTextFromView(device, id):
	hierarchy_viewer=device.getHierarchyViewer()
	view_node = hierarchy_viewer.findViewById(id)
	return hierarchy_viewer.getText(view_node)#.encode("utf8")

def press(device, keycode):
	device.press( keycode,'DOWN_AND_UP')
	MonkeyRunner.sleep(1)

def pressLong(device):
	device.press('KEYCODE_DPAD_CENTER', MonkeyDevice.DOWN)
	MonkeyRunner.sleep(2)
	device.press('KEYCODE_DPAD_CENTER', MonkeyDevice.UP)

def type(device, str):
	device.type(str)
	MonkeyRunner.sleep(1)

def easyTouch(easy_device, id):
	easy_device.touch(By.id(id), 'downAndUp')
	MonkeyRunner.sleep(1)

def clearEditText(device):
	for i in range(20):
		device.press('KEYCODE_DEL', MonkeyDevice.DOWN)
	for i in range(20):
		device.press('KEYCODE_FORWARD_DEL','DOWN_AND_UP')
		
class compImgError(Exception):
	def __init__(self,procName,fatalModel):
		self.procName = procName
		self.errmsg = '< Fatal error:'+self.caseName+' '+fatalModel+'!>'
	
	def __str__(self):
		return self.errmsg


def waitForConnection(deviceId,outpPath):
	device = MonkeyRunner.waitForConnection(deviceId)
	if device:
		printLog('Connect to the device successfully!')
		MonkeyRunner.sleep(1)
		return device
	else:
		printLog('Connect to the device error!')
		sys.exit(1)

def installPackage(device,outpPath,packPath,apkName):
	device.installPackage(packPath+os.sep+apkName)
	printLog('Install apk('+apkName+') successfully!')
	time.sleep(2)

def removePackage(device,outpPath,packName):
	device.removePackage(packName)
	printLog('Uninstall package('+packName+') successfully!')
	time.sleep(2)

def startActivity(device,outpPath,activityName):
	device.startActivity(component = activityName)
	printLog('Start activity ('+activityName+') successfully!')
	time.sleep(3)

def touch(device,touchX,touchY):
	device.touch(touchX,touchY,'DOWN_AND_UP')
	time.sleep(2)

def drag(device,startTuple,endTuple,duration,steps):
	device.drag(startTuple,endTuple,duration,steps)
	time.sleep(3)

def isFatal(device,fatalRect,fatalImgComp,imageName,outpPath,fatalModel):
	fatalImgComp = fatalImgComp.getSubImage(fatalRect)
	fatalImgComp.writeToFile(outpPath+os.sep+'image'+os.sep+imageName+'_'+fatalModel+'_compare_sub.png','png')
	fatalImg = device.takeSnapshot()
	fatalImg0=result.getSubImage(fatalRect)
	fatalImg0.writeToFile(outpPath+os.sep+'image'+os.sep+imageName+'_'+fatalModel+'_sub.png','png')
	if fatalImg0.sameAs(fatalPic,0.9):
		if fatalModel == 'crash':
			raise compImgError(outpPath,'crash')
		else:
			raise compImgError(outpPath,'anr')
		raise compImgError(outpPath,'unkown error') 
	
def sameAs(device,times,rectTuple,imageCompareName,outpPath,imgMap,testSign):
	try:
		printLog("Compare image of " + imageCompareName)
		imageName = imageCompareName + "_" + datetime.now().strftime('%y-%m-%d_%H%M%S')
		imageCompare = imgMap[imageCompareName].getSubImage(rectTuple)
		imageCompare.writeToFile(outpPath+os.sep+imageName+'_compare_sub.png','png')
		for i in range(times):
			image = None
			image=takeSnapshot(device)
			if image == None:
				printLog("Unable to take snapshot, return false")
				testSign = False
			else:
				image0=image.getSubImage(rectTuple)
				image0.writeToFile(outpPath+os.sep+imageName+'_sub.png','png')
				result = image0.sameAs(imageCompare,0.95)
			if testSign:
				result = not result
			if result:
				printLog('Loadpage successfully')
				break
			if not i == times:
				MonkeyRunner.sleep(2)
				printLog('Delay of loading page '+str((i+1)*2)+'s')
			else:
				imageName = imageCompareName + "_" +  datetime.now().strftime('%y-%m-%d_%H%M%S')
				image = takeSnapshot(device)
				if not image == None:
					image.writeToFile(outpPath+os.sep+'whole_'+imageName+'.png','png')
		return result
	except Exception, e:
		printLog("[Compare image error]: " + str(e))
		printLog("[Detail log]: " + str(traceback.format_exc()))

def takeSnapshot(device):
	for i in range(5):
		printLog("TakeSnapshot " + str(i+1) + " time")
		try:
			image = device.takeSnapshot()
			if not image == None:
				return image
		except TimeoutException, e:
			printLog("---------------------------1" + str(e))
			printLog(traceback.format_exc())
			return None
		except Exception, e:
			printLog("---------------------------2" + str(e))
			printLog(traceback.format_exc())
			return None
		MonkeyRunner.sleep(1)
	

def loadImage(path):
	fileMap = {}
	fileList = os.listdir(path)
	for img in fileList:
		fileMap[img.replace(".png", "")] = MonkeyRunner.loadImageFromFile(path+os.sep+img,'png')
	return fileMap

def printLog(log):
	print("[" + datetime.now().strftime('%y-%m-%d %H:%M:%S') + "] " + log)
	
def createFile(path,filename,content):
	if os.path.exists(path+os.sep+filename.encode("utf8")):
		os.remove(path+os.sep+filename)
	file = open(path+os.sep+filename,'w')
	file.write(content)
	file.close()

def main():
	pass
if __name__ == '__main__':
	main()
		